<template>
	<view class="layout">
		<view class="layout-nav" :style="{ height: fixedTop + 'px' }">
			<DistributionNavBar title="素材下载" :rgb="navBarRgba">
				<template slot="left">
					<image :src="bankIcon" @click="clickBack" />
				</template>
			</DistributionNavBar>
		</view>

		<view class="layout-header">
			<CommonMateriaHeader title="下载说明" :list="downloadList" :isSkelett="isSkelett" @callBack="changeHeaderStatus" />
		</view>

		<view class="layout-product">
			<DistributionMaterial :skelettSize="1" :isSkelett="isSkelett" :isFooter="false" :list="singleMaterialList" />
		</view>

		<view class="layout-main">
			<view class="layout-main-tabs">
				<DistributionSubTabs
					height="100rpx"
					:fixedTop="fixedTop"
					v-model="resourceType"
					:list="tabsTypeList"
					:isSkelett="isSkelett"
					ref="DistributionSubTabs"
					@beforeCallBack="changeTypeTabs"
				/>
			</view>

			<view class="layout-main-content">
				<template v-if="isSkelett || isResourceListLength">
					<swiper
						class="swiper"
						skip-hidden-item-layout
						:style="[swiperStyle]"
						:current-item-id="resourceType"
						@animationfinish="changeTabsType"
					>
						<swiper-item
							:item-id="tabItem.type"
							:key="tabItem.type"
							v-for="tabItem in tabsTypeList"
							class="layout-main-content-box-item"
						>
							<MaterialDownloadResource
								:disabled="isLoading"
								:isSkelett="isSkelett"
								:isPreview="false"
								:list="staticFileObject[tabItem.type]"
								@openPreview="openPreview"
								@changeResourceListStatus="changeResourceListStatus"
							/>
						</swiper-item>
					</swiper>
				</template>

				<DistributionHint :type="isHintStatus" :customize="hintCustomize" />
			</view>
		</view>

		<CommonMateriaFooter v-show="!isSkelett">
			<template slot="footerButton">
				<view class="layout-footer">
					<button @click.prevent.stop="openMaterialUpload" class="free-download">上传素材</button>
					<button
						:loading="isLoading"
						:disabled="isSubmitReview || isLoading"
						:class="{
							active: isLoading,
							disabled: isSubmitReview
						}"
						@click.prevent.stop="startDownloadStatus"
					>
						<text>一键下载</text>
						<text class="layout-footer-subLable" v-if="selectedFileNumber">(已选{{ selectedFileNumber }})</text>
					</button>
				</view>
			</template>
		</CommonMateriaFooter>

		<DistributionCommonPopup v-model="isPopup" :disabled="isPopupLoading">
			<view class="layout-popup">
				<view class="layout-popup-money">
					￥
					<text>{{ billingParams.priceYuan }}</text>
				</view>

				<view class="layout-popup-hint">已选图片{{ billingParams.image }}张、视频{{ billingParams.video }}份</view>

				<view class="layout-popup-balance">
					<view class="layout-popup-balance-item">
						<image src="@/static/icon/icon_tc_download.png" />
						当前免费下载次数剩余
						<text>{{ billingParams.freeDownload }}</text>
						次
					</view>
					<view class="layout-popup-balance-item">
						<image src="@/static/icon/icon_tc_money.png" />
						钱包余额
						<text>¥{{ billingParams.balanceYuan }}</text>
					</view>
				</view>

				<view class="layout-popup-footer layout-footer">
					<template v-if="billingParams.freeDownload || isBalanceButton">
						<button
							class="free-download"
							@click.prevent.stop="submitBuyResource(99)"
							:class="{ disabled: !billingParams.freeDownload }"
							:disabled="isPopupLoading || !billingParams.freeDownload"
							:loading="isPopupLoading && billingParams.payType === 99"
						>
							免费下载
						</button>
					</template>

					<template v-if="isBalanceButton">
						<button
							class="balance-download"
							:class="{
								active: billingParams.payType === 4,
								disabled: billingParams.payType === 99
							}"
							:disabled="isPopupLoading"
							@click.prevent.stop="submitBuyResource(4)"
							:loading="isPopupLoading && billingParams.payType === 4"
						>
							余额下载
						</button>
					</template>

					<template v-else>
						<button
							class="immed-download"
							:class="{
								prohibit: modelIsIos,
								active: billingParams.payType === 3,
								disabled: billingParams.payType === 99
							}"
							:disabled="isPopupLoading"
							@click.prevent.stop="submitBuyResource(3)"
							:loading="isPopupLoading && billingParams.payType === 3"
						>
							{{ modelIsIos ? '抱歉，苹果手机暂不支持哦～' : '立即下载' }}
						</button>
					</template>
				</view>
			</view>
		</DistributionCommonPopup>

		<DistributionResourcePreview
			remote
			frequency
			v-model="isPreviewPopup"
			:list="previewList"
			:index="previewCurrentIndex"
			@changeIndex="changePreviewCurrentIndex"
		/>
	</view>
</template>

<script>
import { debounce } from 'lodash';
import { isIos, getSystemInfo, defaultImageUrl } from '@/utils';
import { buyMaterial, getQueryAllDetail, getFreeDownloadAndBalance, getSingleProductDetail } from '@/api/material';
import { requestPayment, isMultipleAuthor, secondFormatMinute, formatCommissionsModel, getMaterialFileSize } from '@/utils/common';

import DistributionHint from '@/components/distributionHint';
import CommonMateriaFooter from './components/CommonMateriaFooter';
import CommonMateriaHeader from './components/CommonMateriaHeader';

import DistributionSubTabs from '@/components/distributionSubTabs';
import DistributionMaterial from '@/components/distributionMaterial';

import DistributionNavBar from '@/components/distributionNavBar/indeHome';
import MaterialDownloadResource from './components/MaterialDownloadResource';

import DistributionCommonPopup from '@/components/distributionCommonPopup';
import DistributionResourcePreview from '@/components/distributionResourcePreview';

const bankIcon = Object.freeze(`${defaultImageUrl}help/icon_navbar_back.png`);
const hintBgImageUrl = Object.freeze(`${defaultImageUrl}image/img_nopic.png`);

const hintCustomize = Object.freeze({
	nodata: {
		label: '暂无素材，去上传试试看～',
		imagrUrl: hintBgImageUrl
	}
});

const errorHintList = [
	{
		type: 1,
		hint: '产品不存在；'
	},
	{
		type: 2,
		hint: '产品已下架；'
	},
	{
		type: 3,
		hint: '资源已下架；'
	},
	{
		type: 4,
		hint: '资源已售罄；'
	},
	{
		type: 5,
		hint: '资源审批未通过；'
	},
	{
		type: 6,
		hint: '资源不存在；'
	},
	{
		type: 7,
		hint: '图片或视频数量小于最小购买限制；'
	},
	{
		type: 8,
		hint: '图片数量超过最大购买限制；'
	},
	{
		type: 9,
		hint: '图片或视频数量小于最小购买限制；'
	},
	{
		type: 10,
		hint: '视频数量超过最大购买限制；'
	}
];

const { itemSize, marginLeft, widthHeight } = getMaterialFileSize();

// 顶部导航 rgba
const speed = 80;
const modelIsIos = isIos();

const { statusBarHeight } = getSystemInfo();
const fixedTop = Object.freeze((modelIsIos ? 44 : 48) + statusBarHeight);

export default {
	name: 'MaterialDownload',

	data() {
		this.selectedBeyondHint = '';

		this.debounced = debounce((scrollTop) => {
			this.scrollTop = scrollTop;
		}, 10);

		return {
			fixedTop,
			bankIcon,
			modelIsIos: false,

			hintCustomize,

			scrollTop: 0,
			isPopup: false,
			isSkelett: true,

			// resourceType: '',
			productId: null,
			singleMaterialList: [],
			materialResourceList: [],

			requestParams: {
				pageIndex: 1,
				uploadType: 1,
				pageSize: 50
			},

			isLoading: false,
			isHintStatus: '', // nomore  nodata

			otherParams: {},
			billingParams: {},
			isPopupLoading: false,

			downloadList: [{}, {}, {}, {}],

			staticFileInfo: {},

			scrollViewScrollTop: 0,
			resourceType: 'allResource',

			previewList: [],
			isPreviewPopup: false,
			previewCurrentIndex: 0,

			selectedImageNumber: 0,
			selectedVideoNumber: 0
		};
	},

	onLoad(params) {
		this.productId = Number(params?.productId || 0);

		this.getProductDetail();
		this.getCurrentPageData();
	},

	computed: {
		navBarRgba() {
			const { scrollTop } = this;

			const opacity = (scrollTop / speed).toFixed(2);

			return `rgba(255, 255, 255, ${opacity})`;
		},

		isResourceListLength() {
			const { materialResourceList } = this;

			return materialResourceList.length;
		},

		isSubmitReview() {
			const {
				materialResourceList,
				otherParams: { imgMinBuy, videoMinBuy }
			} = this;

			const formatList = materialResourceList.filter((item) => item.isActive);

			if (!formatList.length) {
				return true;
			}

			let imageNumber = 0;
			let videoNumber = 0;

			formatList.forEach((item) => {
				const { resourceType } = item;

				resourceType === 2 ? ++videoNumber : ++imageNumber;
			});

			if (!imageNumber && !videoNumber) {
				return true;
			}

			if ((imageNumber && imageNumber < imgMinBuy) || (videoNumber && videoNumber < videoMinBuy)) {
				return true;
			}

			return false;
		},

		isBalanceButton() {
			const {
				billingParams: { price, balance }
			} = this;

			return balance >= price;
		},

		swiperStyle() {
			const { isSkelett, isResourceListLength } = this;

			const maxLength = isSkelett ? 2 : Math.ceil((isResourceListLength || 1) / itemSize);

			return {
				height: `${maxLength * (marginLeft + widthHeight)}px`
			};
		},

		tabsTypeList() {
			const {
				staticFileInfo: { imgNum, videoNum }
			} = this;

			return [
				{
					// type: '',
					label: '全部',
					type: 'allResource'
				},
				{
					// type: '1',
					label: '图片',
					type: 'imgResource',
					subLabel: imgNum && `(${imgNum})`
				},
				{
					// type: '2',
					label: '视频',
					type: 'videoResource',
					subLabel: videoNum && `(${videoNum})`
				}
			];
		},

		staticFileObject() {
			const { materialResourceList } = this;

			let imgResource = [];
			let videoResource = [];

			materialResourceList.forEach((item) => (item.resourceType === 2 ? videoResource.push(item) : imgResource.push(item)));

			return {
				imgResource,
				videoResource,
				allResource: materialResourceList
			};
		},

		selectedFileNumber() {
			const { selectedImageNumber, selectedVideoNumber } = this;

			return selectedImageNumber + selectedVideoNumber;
		}
	},

	methods: {
		getCurrentPageData(pageIndex = this.requestParams.pageIndex) {
			const { isSkelett, productId, requestParams, resourceType } = this;

			const params = {
				...requestParams,
				productId,
				pageIndex
				// resourceType
			};

			getQueryAllDetail(params).then((res) => {
				const { code, data } = res;

				if (code !== 200) {
					return;
				}

				const { imgNum, videoNum, bothResource } = data;

				const filterList = (bothResource || []).map((item) => {
					const { duration, ...otherParams } = item;

					return Object.assign(
						otherParams,
						duration && {
							duration: secondFormatMinute(duration)
						}
					);
				});

				this.materialResourceList = filterList;
				this.staticFileInfo = {
					imgNum,
					videoNum
				};
				this.isHintStatus = 'nomore';

				this.$nextTick((e) => {
					isSkelett &&
						setTimeout((e) => {
							this.changeHeaderStatus();
						}, 10);

					this.isSkelett = false;
				});

				return;

				// const isPageIndex = pageIndex === 1;
				// const filterList = (data?.data || []).map((item) => {
				// 	const { duration, ...otherParams } = item;

				// 	return Object.assign(
				// 		otherParams,
				// 		duration && {
				// 			duration: secondFormatMinute(duration)
				// 		}
				// 	);
				// });

				// this.requestParams.pageIndex = pageIndex;
				// this.materialResourceList = isPageIndex ? filterList : [...this.materialResourceList, ...filterList];

				// this.isHintStatus =
				// 	isPageIndex && !filterList.length ? 'nodata' : filterList.length < requestParams.pageSize ? 'nomore' : '';

				// this.$nextTick((e) => {
				// 	isSkelett &&
				// 		setTimeout((e) => {
				// 			this.changeHeaderStatus();
				// 		}, 10);

				// 	this.isSkelett = false;
				// });
			});
		},

		changeTypeTabs(params) {
			this.resourceType = params.type;
			// const {
			// 	scrollTop,
			// 	$refs: { DistributionSubTabs }
			// } = this;

			// const duration = 3000;
			// const diff = DistributionSubTabs.mainTop - fixedTop;

			// if (diff - scrollTop < 0) {
			// 	uni.pageScrollTo({
			// 		duration,
			// 		scrollTop: diff,
			// 		success: (res) => {
			// 			setTimeout((e) => {
			// 				this.resourceType = params.type;
			// 			}, duration);
			// 		}
			// 	});
			// 	return;
			// }
		},

		changeTabsType(params) {
			const { resourceType } = this;
			const { currentItemId } = params.detail;

			if (resourceType === currentItemId) {
				return;
			}

			this.resourceType = currentItemId;
		},

		openMaterialUpload() {
			const { productId } = this;
			const url = `/materialPage/MaterialUpload?productId=${productId}`;

			uni.navigateTo({
				url
			});
		},

		changeResourceListStatus({ id }) {
			const {
				selectedImageNumber,
				selectedVideoNumber,

				selectedBeyondHint,
				materialResourceList,
				otherParams: { imgMaxBuy, videoMaxBuy }
			} = this;
			const index = materialResourceList.findIndex((item) => item.id === id);

			const singleItem = materialResourceList[index];
			const isVideo = singleItem.resourceType === 2;

			if (!singleItem.isActive) {
				if ((isVideo && selectedVideoNumber === videoMaxBuy) || (!isVideo && selectedImageNumber === imgMaxBuy)) {
					uni.showModal({
						title: '提示',
						showCancel: false,
						content: selectedBeyondHint
					});
					return;
				}
			}

			this[isVideo ? 'selectedVideoNumber' : 'selectedImageNumber'] =
				(isVideo ? selectedVideoNumber : selectedImageNumber) + (!singleItem.isActive ? 1 : -1);

			this.$set(singleItem, 'isActive', !singleItem.isActive);
		},

		changeHeaderStatus() {
			this.$refs.DistributionSubTabs?.getMainLableDomeInfo?.();
		},

		startDownloadStatus() {
			const { isLoading, materialResourceList } = this;
			const status = isMultipleAuthor();

			if (isLoading || !status) {
				return;
			}

			this.isLoading = true;

			let statusNumObject = {
				image: 0,
				video: 0
			};

			const formatList = materialResourceList.filter((item) => item.isActive);

			const resourceIdList = formatList.map((item) => item.id);
			const totalPrice = formatList.reduce((previous, current) => {
				const { resourceType, price } = current;
				const type = resourceType === 2 ? 'video' : 'image';
				statusNumObject[type] = ++statusNumObject[type];

				return previous + price;
			}, 0);

			getFreeDownloadAndBalance()
				.then((res) => {
					const { code, data } = res;

					if (code !== 200) {
						return;
					}

					const { balance, balanceYuan, freeDownload = 0 } = data || {};

					this.billingParams = {
						...statusNumObject,
						resourceIdList,

						balance,
						balanceYuan,

						freeDownload,

						price: totalPrice,
						priceYuan: totalPrice / 100
					};

					this.isPopup = true;
				})
				.finally((e) => {
					this.isLoading = false;
				});
		},

		/**支付方式:1-微信 2-支付宝 3-易宝 4-余额 5-授信 6-抖音 7-银行卡 99-免费下载次数 */
		submitBuyResource(payType = 99) {
			const { modelIsIos, billingParams, isPopupLoading, singleMaterialList } = this;
			const [{ id, productTitle }] = singleMaterialList;

			if (isPopupLoading || modelIsIos) {
				return;
			}

			this.isPopupLoading = true;
			this.$set(billingParams, 'payType', payType);

			const requestParams = [
				{
					skuId: '',
					skuName: '',

					payType,
					productId: id,
					productName: productTitle,

					resourceIdList: billingParams.resourceIdList
				}
			];

			buyMaterial(requestParams)
				.then((res) => {
					const { code, data } = res || {};

					if (code !== 200) {
						return;
					}

					const { errorType, orderNo } = data || {};
					const singleHint = errorHintList.find((item) => item.type === errorType);

					if (singleHint) {
						uni.showToast({
							mask: true,
							icon: 'none',
							title: singleHint.hint
						});

						this.isPopupLoading = false;
						return;
					}

					if (payType === 3) {
						// const {paySign, signType, nonceStr, timeStamp, packageValue} = data;
						requestPayment(data).then((res) => {
							if (!res) {
								this.isPopupLoading = false;
								return;
							}

							this.openOrderDetailPage({
								id,
								orderNo,
								approveStatus: null
							});
						});
						return;
					}

					this.openOrderDetailPage({
						id,
						orderNo
					});
				})
				.catch((e) => {
					this.isPopupLoading = false;
				});
		},

		getProductDetail() {
			const { productId } = this;
			getSingleProductDetail({ productId }).then((res) => {
				const { code, data } = res || {};

				if (code !== 200) {
					return;
				}

				const { commission, productName, productConfig, ...otherParams } = data;

				this.singleMaterialList = [
					{
						id: productId,
						...otherParams,
						productTitle: productName,
						commissionsList: formatCommissionsModel(commission)
					}
				];

				const formatProductConfig = this.formatProductConfig(productConfig);

				this.otherParams = formatProductConfig;

				const imageSelectedBeyondHint = `图片最小下载数为${formatProductConfig.imgMinBuy}、视频最小下载数为${formatProductConfig.videoMinBuy}`;
				const videoSelectedBeyondHint = `图片最大下载数${formatProductConfig.imgMaxBuyLabel}、视频最大下载数${formatProductConfig.videoMaxBuyLabel}`;

				this.downloadList = [
					{
						label: imageSelectedBeyondHint
					},
					{
						label: videoSelectedBeyondHint
					},
					{
						label: '下载的图片素材、视频素材可作为探店视频原材料进行创作剪辑'
					},
					{
						label: '剪辑后的探店视频可在抖音、快手等平台发布获得持续佣金收入'
					}
				];
				this.selectedBeyondHint = imageSelectedBeyondHint + videoSelectedBeyondHint;
			});
		},

		openOrderDetailPage({ id, orderNo, approveStatus = 1 }) {
			const url = `/materialPage/MaterialOrderBuy?orderId=${id}&approveStatus=${approveStatus}&cartOrderNo=${orderNo}`;

			uni.navigateTo({
				url,
				success: (e) => {
					this.isPopup = false;
					this.isPopupLoading = false;

					this.selectedImageNumber = 0;
					this.selectedVideoNumber = 0;

					this.materialResourceList.forEach((item) => {
						item.isActive && this.$set(item, 'isActive', false);
					});
				}
			});
		},

		clickBack() {
			uni.navigateBack();
		},

		formatProductConfig({ imgMinBuy, videoMinBuy, ...otherParams }) {
			let formatParams = {
				imgMinBuy,
				videoMinBuy
			};

			['imgMaxBuy', 'videoMaxBuy'].forEach((key) => {
				const value = otherParams[key];
				const isUnlimited = value < 1;

				formatParams[key] = isUnlimited ? 999 : value;

				formatParams[key + 'Label'] = isUnlimited ? '不限' : `为${value}`;
			});

			return formatParams;
		},

		openPreview({ previewList, previewCurrentIndex }) {
			this.previewCurrentIndex = previewCurrentIndex;
			this.previewList = previewList;

			this.isPreviewPopup = true;
		},

		changePreviewCurrentIndex(index) {
			this.previewCurrentIndex = index;
		}
	},

	onReachBottom() {
		const {
			isSkelett,
			isHintStatus,
			requestParams: { pageIndex }
		} = this;

		if (isHintStatus || isSkelett) {
			return;
		}

		this.isHintStatus = 'loading';
		this.getCurrentPageData(pageIndex + 1);
	},

	onPageScroll({ scrollTop }) {
		this.debounced?.(scrollTop);
		this.$refs.DistributionSubTabs?.changePageScroll?.(scrollTop);
	},

	components: {
		DistributionHint,
		DistributionNavBar,
		DistributionSubTabs,

		CommonMateriaHeader,
		DistributionMaterial,
		CommonMateriaFooter,
		MaterialDownloadResource,
		DistributionCommonPopup,
		DistributionResourcePreview
	}
};
</script>

<style lang="scss" scoped>
@import '@/style/common.scss';

.layout {
	min-height: 100vh;
	background: #fff;
	@include Db_iosBottomDistance(140rpx);

	&::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 740rpx;
		background: linear-gradient(180deg, #fff9f1 0%, #fff0dd 100%);
	}

	// 弹框提示
	&-popup {
		padding: 0 28rpx;
		margin-top: -16rpx;

		&-money {
			text-align: center;

			color: #333;
			font-size: 40rpx;
			font-weight: bold;

			text {
				font-size: 72rpx;
				font-family: font-number;
			}
		}

		&-hint {
			color: #666;
			font-size: 28rpx;
			text-align: center;
			margin-top: 16rpx;
		}

		&-balance {
			margin-top: 48rpx;
			padding: 26rpx 24rpx;

			&-item {
				display: flex;
				align-items: center;
				margin-top: 28rpx;

				color: #333;
				font-size: 24rpx;

				image {
					width: 28rpx;
					height: 28rpx;
					margin-right: 18rpx;
				}

				text {
					margin: 0 6rpx;
					color: #ff6b11;
					font-weight: bold;
				}

				&:first-child {
					margin-top: 0;
				}
			}
		}

		&-footer {
			margin: 48rpx -28rpx 16rpx;
		}
	}

	&-nav {
		image {
			width: 40rpx;
			height: 40rpx;
			padding: 20rpx 20rpx 20rpx 0;
		}
	}

	&-header {
		position: relative;
		padding: 20rpx 20rpx 0;
	}

	&-product {
		position: relative;
		margin-top: 20rpx;
		padding: 0 20rpx;
	}

	&-main {
		position: relative;
		margin-top: 20rpx;

		background: #fff;
		border-radius: 24rpx 24rpx 0 0;

		&-tabs {
			height: 100rpx;
		}

		&-content {
			// margin-top: -14rpx;
		}
	}

	&-footer {
		display: flex;
		padding: 0 28rpx;

		button {
			flex: 1;
			@include Db_commonButton(80rpx, 24rpx);

			background: #ff6b11;

			&.free-download {
				margin-right: 10rpx;
				background: #fff;
				color: #ff6b11;
				border: 2rpx solid #ff6b11;

				&.disabled {
					color: #fff;
					border-color: #ccc;
					background: #ccc;
				}
			}

			&:last-child {
				margin-left: 10rpx;
			}

			&.disabled,
			&.prohibit {
				background: #ccc;
			}

			&.immed-download,
			&.balance-download {
				&.active {
					background: rgba(255, 107, 17, 0.7);
				}

				&.disabled {
					background: #ff6b11;

					&:active {
						background: #ff6b11;
					}
				}
			}
		}

		&-subLable {
			font-size: 22rpx;
		}
	}
}
</style>
